
const { domain } = require('../config/index');
const axios = require('axios');
const util = require('../utils/util.js');
const cheerio = require('cheerio');

const TiHuanImages = async (content = '') => {
	const c = cheerio.load(content);

	// 选择所有图片元素并获取它们的 src 属性
	const imageSrcList = [];
	c('img').each((index, element) => {
		const src = c(element).attr('src');
		if (src) {
			imageSrcList.push(src);
		}
	});
	console.log('imageSrcList', imageSrcList)

	// 替换图片链接为新链接
	const newBaseUrl = 'https://example.com/new-base-url/';
	imageSrcList.forEach((src, index) => {
		// 构建新的图片链接
		const newSrc = newBaseUrl + 'new-image-' + (index + 1) + '.png';
		// 替换原始 HTML 中的图片链接
		c('img').eq(index).attr('src', newSrc);
	});
	return c.html()
}

const GetDetails = async (url = '/code/detail2866.html') => {
	url = domain + url;
	const resp = await axios.get(url);
	const $ = cheerio.load(resp.data);
	const downLink = $(".down-info .btn .down").first().attr('href');
	const title = $(".show-title h1").clone().find('i').remove().end().text().trim();
	const sourceCodeCategory = $(".lei li:contains('源码分类') a").text().trim();
	const content = $(".show-body #wrap").html();
	const downImgSrc = $(".down-img").attr("src");

	//查重
	const total = await global.db('article').count({ total: 1 }).where({ name: title, source: url }).then(res => {
		return res[0].total;
	})
	if (total) {
		return
	}

	const time = new Date();

	const data = {
		name: title,
		download_url: downLink,
		cat_name: sourceCodeCategory,
		content,
		preview_image: downImgSrc,
		source: url,
		created_at: time,
		is_publish: 0
	}
	console.log('写入数据===>', time.getFullYear() + '-' + time.getMonth() + '+' + time.getDay() + ' ' + time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds(), title)
	await global.db('article').insert(data);


}
module.exports = { GetDetails }